/**
 * Copyright 2008 Matthew DeLambo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.delambo.drool.pooling;

import java.sql.*;
import com.delambo.drool.interfaces.*;

/**
 * Implements Resource and encapsulates a java.sql.Connection.
 * @author delambo
 * @param T type of encapsulated resource.
 */
public class ConnectionResource_Impl<T extends java.sql.Connection> 
        implements Resource<java.sql.Connection> {
    final private T t;
    final private boolean autoCommit;
    
    public ConnectionResource_Impl(T t, boolean autoCommit) {
        this.t = t;
        this.autoCommit = autoCommit;
    }
     
    /**
     * Returns the JDBC connection.
     * @return binded resource.
     */
    public T getResource() {
        return this.t;
    }
    
    /**
     * Closes the JDBC connection.
     */
    public void kill() {
        try { 
            if(t != null) 
                t.close();
        } catch(SQLException sqe) { 
            throw new RuntimeException("Problem occurred when trying to close "
                    + "connection: ", sqe);
        }
    }
    
    /**
     * Runs validation by setting auto commit to check for connectivity.
     * @return true if validation passes.
     */
    public boolean validate() {
        try {
            t.setAutoCommit(autoCommit);
        } catch(SQLException sqe) {
            throw new RuntimeException("Problem validating connection with " +
                    "autocommit: ", sqe);
        }
        return true;
    }
    
    /**
     * Clears JDBC connection warnings.
     */
    public void clean() {
        try {
            t.clearWarnings();
        } catch(SQLException sqe) {
            throw new RuntimeException("Problem cleaning connection warnings: ", 
                    sqe);
        }
    }
}
